package org.codehaus.activemq.transport.jxta;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.URI;
import java.net.UnknownHostException;
import javax.jms.JMSException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.activemq.message.WireFormat;
import org.codehaus.activemq.transport.tcp.TcpTransportServerChannel;
import org.p2psockets.P2PInetAddress;
import org.p2psockets.P2PServerSocket;

public class JxtaTransportServerChannel extends TcpTransportServerChannel
{
  private static final Log log = LogFactory.getLog(JxtaTransportServerChannel.class);

  public JxtaTransportServerChannel(WireFormat wireFormat, URI bindAddr)
    throws JMSException
  {
    super(wireFormat, bindAddr);
  }

  public String toString()
  {
    return "P2pTransportServerChannel@" + this.bindAddressURI;
  }

  protected ServerSocket createServerSocket(URI bind) throws UnknownHostException, IOException {
    ServerSocket answer = null;
    String host = bind.getHost();

    if ((host == null) || (host.length() == 0) || (host.equals("localhost"))) {
      InetAddress addr = P2PInetAddress.getLocalHost();
      answer = new P2PServerSocket(bind.getPort(), getBacklog(), addr);
    }
    else {
      InetAddress addr = P2PInetAddress.getByName(host);
      answer = new P2PServerSocket(bind.getPort(), getBacklog(), addr);
    }

    return answer;
  }
}